package top.lyc829.zzl_android.logic.util;


import android.content.Context;
import android.util.Pair;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import top.lyc829.zzl_android.logic.network.SignInterceptor;
import top.lyc829.zzl_android.logic.network.TokenInterceptor;

public class HttpUtil {

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    private OkHttpClient client;
    private volatile static HttpUtil mClient;
    private Context context;
    private HttpUtil(Context c) {
        context = c;
        client = new OkHttpClient.Builder()
//                .cookieJar(new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context)))
                .followRedirects(true)
                .followSslRedirects(true)
                .addInterceptor(new SignInterceptor())
                .addInterceptor(new TokenInterceptor())
                .build();
    }

    public static HttpUtil getInstance(Context c){

        // DCL 饿汉单例，Double Check Lock
        if (mClient == null) {
            synchronized (HttpUtil.class) {
                if (mClient == null) {
                    mClient = new HttpUtil(c);
                }
            }
        }


        return  mClient;
    }

    /**
     * get同步请求
     * @param url 地址
     * @param param 参数
     * @return String
     * @throws IOException
     */
    public String getSync(String url, HashMap<String, String> param) throws IOException {

        FormBody.Builder formBody = new FormBody.Builder();
        if(!param.isEmpty()) {
            for (Map.Entry<String,String> entry: param.entrySet()) {
                formBody.add(entry.getKey(),entry.getValue());
            }
        }
        RequestBody form = formBody.build();

        Request.Builder builder = new Request.Builder().url(url);
        builder.method("GET", form);
        Request request = builder.build();
        Call call = client.newCall(request);
        return call.execute().body().string();
    }

    // GET方法
    public void get(String url, HashMap<String,String> param, MyCallback callback) {
        // 拼接请求参数
        if (!param.isEmpty()) {
            StringBuffer buffer = new StringBuffer(url);
            buffer.append('?');
            for (Map.Entry<String,String> entry: param.entrySet()) {
                buffer.append(entry.getKey());
                buffer.append('=');
                buffer.append(entry.getValue());
                buffer.append('&');
            }
            buffer.deleteCharAt(buffer.length()-1);
            url = buffer.toString();
        }
        Request.Builder builder = new Request.Builder().url(url);
        builder.method("GET", null);
        Request request = builder.build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.failed(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    callback.failed(new IOException(response.message()));
                    response.close();
                } else {
                    callback.success(response);
                }
            }
        });
    }

    public void get(String url, MyCallback callback) {
        get(url, new HashMap<String, String>(), callback);
    }

    /**
     * Post方法，传递json数据
     * @param url 地址
     * @param json json字符串
     * @param callback 回调
     */
    public void postJson(String url, String json, MyCallback callback) {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                callback.failed(e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (!response.isSuccessful()) {
                    callback.failed(new IOException(response.message()));
                    response.close();
                } else {
                    callback.success(response);
                }
            }
        });
    }

    // POST 方法
    public void post(String url, HashMap<String, String> param, MyCallback callback) {
        FormBody.Builder formBody = new FormBody.Builder();
        if(!param.isEmpty()) {
            for (Map.Entry<String,String> entry: param.entrySet()) {
                formBody.add(entry.getKey(),entry.getValue());
            }
        }
        RequestBody form = formBody.build();
        Request.Builder builder = new Request.Builder();
        Request request = builder.post(form)
                .url(url)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.failed(e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                if (!response.isSuccessful()) {
                    callback.failed(new IOException(response.message()));
                    response.close();
                } else {
                    callback.success(response);
                }
            }
        });
    }

    /**
     * 上传图片
     * @param url 路径
     * @param file 图片
     * @param callback 回调
     */
    public void uploadPhoto(String url, File file, MyCallback callback) {

        RequestBody fileBody = RequestBody.create(MEDIA_TYPE_PNG, file);

        Request request = new Request.Builder()
                .url(url)
                .post(fileBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                callback.failed(e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (!response.isSuccessful()) {
                    callback.failed(new IOException(response.message()));
                    response.close();
                } else {
                    callback.success(response);
                }
            }
        });

    }

    /**
     * 上传多图和参数
     * @param url 地址
     * @param params 参数
     * @param fileList 图片file列表
     * @param callback 回调
     */
    public void sendMultipart(String url, Map<String, String> params, List<Pair<String, File>> fileList, MyCallback callback) {
        MultipartBody.Builder mbody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                mbody.addFormDataPart(key, params.get(key));
            }
        }
        if (fileList != null && !fileList.isEmpty()) {
            for(Pair<String, File> pair:fileList){
                if(pair.second.exists()){
                    mbody.addFormDataPart(pair.first,pair.second.getName(),RequestBody.create(MEDIA_TYPE_PNG,pair.second));
                }
            }
        }

        Request request = new Request.Builder()
                .url(url)
                .post(mbody.build())
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                callback.failed(e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (!response.isSuccessful()) {
                    callback.failed(new IOException(response.message()));
                    response.close();
                } else {
                    callback.success(response);
                }
            }
        });
    }

    /**
     * 上传单图和参数
     * @param url 地址
     * @param params 参数
     * @param file 文件
     * @param fileName 文件名
     * @param callback 回调
     */
    public void sendSingleFileWithParams(String url, Map<String, String> params, File file, String fileName, MyCallback callback) {
        MultipartBody.Builder mbody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                mbody.addFormDataPart(key, params.get(key));
            }
        }

        if(file.exists()){
            mbody.addFormDataPart(fileName, file.getName(),RequestBody.create(MEDIA_TYPE_PNG,file));
        }


        Request request = new Request.Builder()
                .url(url)
                .post(mbody.build())
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                callback.failed(e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (!response.isSuccessful()) {
                    callback.failed(new IOException(response.message()));
                    response.close();
                } else {
                    callback.success(response);
                }
            }
        });
    }





    public interface MyCallback {
        void success(Response res) throws IOException;
        void failed(IOException e);
    }

}